
import AStarMap from "./AStarMap";
import SingtonBase from "./SingtonBase";

/**
* @ name:AStarFinder
* @ desc:A* 寻路插件
* @ user:By NUOLO
* @ data: 2020-12-29 18:19
*/
export default class AStarFinder extends SingtonBase {
    private m_AStarMap: AStarMap;
    private m_AStar;
    private graph: Graph;
    private astarFindPath: GridNode[];
    public Init() {
    }
    public SetAStarMap(AStarMap:AStarMap) {
        if (!this.graph) {
            this.m_AStarMap = AStarMap;
            this.graph = new Graph(this.m_AStarMap.matrix);
        }
        this.Searchtest();
    }

    public Search(start, end) {
        this.astarFindPath=  astar.search(this.graph, this.VecToMatrix(start), this.VecToMatrix(end)) ;
        return this.MatrixToVec();
    }

    public VecToMatrix(pos:Laya.Vector3):any {
        let t = 100;
        let x=0,y=0;
        for (let i = 0; i <  this.m_AStarMap.poslist.length; i++) {
            for (let j = 0; j < this.m_AStarMap.poslist[i].length; j++) {
                let tp = this.m_AStarMap.poslist[i][j]; //获得坐标
                
                let a = Math.abs(pos.x - tp.x / 1000);
                let b = Math.abs(pos.y - tp.y / 1000);
                let c = Math.abs(pos.z - tp.z / 1000);
                if (t>(a+b+c)) {
                    t = (a + b + c);
                    x = i; y = j;
                }
            }
        }
        return  this.graph.grid[x][y];
    }

    public MatrixToVec():Laya.Vector3[] {
        let poslist = [];
        for (let i = 0; i < this.astarFindPath.length; i++) {
            let t = this.m_AStarMap.poslist[this.astarFindPath[i].x][this.astarFindPath[i].y];
            poslist.push(new Laya.Vector3(t.x / 1000, t.y / 1000, t.z / 1000));
        }
        return poslist;
    }

    public Searchtest() {
        let a = this.graph.grid[1][0];
        let x=this.graph.grid[1][10]
        return console.log(astar.search(this.graph, a, x));
    }
}